#include "mz_md5_list.h"
#include "comm_def.h"
#include "md5.h"
#include "mz_file_info.h"
#include "mz_debug.h"

#include <string.h>
#include <stdio.h>
#include <windows.h> 

#define  MD5_INFO_CNT_DEF 512

static unsigned int _save_cnt = 0;

typedef struct md5info_t {
	char*			md5;
	char*			path;
	unsigned int	path_len;
} MD5_INFO;
static MD5_INFO* _pInfo = 0;

static void _save_md5(unsigned char* md5, char* file_path, unsigned int len) {
	static unsigned int max_save_cnt = MD5_INFO_CNT_DEF;
	int i = 0;

	if(_save_cnt>= max_save_cnt) {
		_pInfo = (MD5_INFO*)realloc(_pInfo, (max_save_cnt + 256) * sizeof(MD5_INFO));
		max_save_cnt += 256;
	}
	_pInfo[_save_cnt].md5 = (char*)malloc(32 + 1);
	
	for (; i < 32; ++i) {
		_pInfo[_save_cnt].md5[i] = md5[i];
	}
	_pInfo[_save_cnt].md5[i] = '\0';

	_pInfo[_save_cnt].path_len = len;
	_pInfo[_save_cnt].path = (char*)malloc(len + 1);
	sprintf(_pInfo[_save_cnt].path, "%s", file_path);
	++_save_cnt;
	return;
}


static int _save_md5_list_to_file(char* target_path) {
	FILE* f = fopen(target_path, "w");
	char buf[2048] = {0};
	unsigned int i = 0;
	if(0 != f) {
		memset(buf, 0, sizeof(buf));
		for (; i < _save_cnt; ++i) {
			sprintf(buf, "%s,%s\n", _pInfo[i].md5, _pInfo[i].path);
			fwrite(buf, 32 + _pInfo[i].path_len + 2, 1, f);
		}
	} else {
		printf("can not create md5-list file.\nanny key to exit.\n");
		getchar();
		exit(-1);
	}
	fclose(f);
	return MZ_RESULT_OK;
}

static char* _get_filepath_in_zip (char* pstr) {
	char* psplit = strchr(pstr, ':');
	if(psplit) {
		pstr = psplit + 1;
	}

	while('.' == *pstr || '\\' == *pstr || '/' == *pstr) {
		++pstr;
	}
	return pstr;
}

extern char* MDFile(char*); //vs 2008 bug?
int mz_make_md5_list() {
	MZ_NODE_T* flist_it = mz_get_file_list_info_first();
	unsigned char* curmd5 = 0;

	_pInfo = (MD5_INFO*)malloc(MD5_INFO_CNT_DEF * sizeof(MD5_INFO));

	while (!mz_is_end_of_list(flist_it)) {
		char* pzip_path = 0;
		curmd5 = MDFile(flist_it->path);

		pzip_path = _get_filepath_in_zip(flist_it->path);
		_save_md5(curmd5, pzip_path, strlen(pzip_path));
		flist_it = mz_get_next_info(flist_it);
	}

	_save_md5_list_to_file("_md5list.txt");
	return 0;
}